package com.picket.controller.matches;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import com.picket.domain.FileUpload;
import com.picket.domain.Match;
import com.picket.service.IEventService;
import com.picket.service.IMatchService;

@Controller
@RequestMapping(value = "/admin/matches")
public class MatchUploadController {
	
	  @ModelAttribute("matchesUploadForm")
	  public MatchUploadForm createForm() {
	    return new MatchUploadForm();
	  }
	  
	  
	private IEventService eventService;

	@Required
	public void setEventService(IEventService eventService) {
		this.eventService = eventService;
	}

	  
	private IMatchService matchService;

	@Required
	public void setMatchService(IMatchService matchService) {
		this.matchService = matchService;
	}
	
	private String uploadFolderPath;
	ServletConfig config;

	public String getUploadFolderPath() {
		return uploadFolderPath;
	}

	public void setUploadFolderPath(String uploadFolderPath) {
		this.uploadFolderPath = uploadFolderPath;
	}

	@RequestMapping(value="upload",method = RequestMethod.GET)
	public String getUploadForm(Model model) {
		model.addAttribute(new FileUpload());
		model.addAttribute("events", eventService.getAllEvents());
		return "/matches/uploadMatches";
	}

	@RequestMapping(value="upload",method = RequestMethod.POST)
	public String create(MatchUploadForm form, BindingResult result,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
		if (result.hasErrors()) {
			for (ObjectError error : result.getAllErrors()) {
				System.err.println("Error: " + error.getCode() + " - "
						+ error.getDefaultMessage());
			}
			return "/matches/uploadMatches";
		}

		// Some type of file processing...
		System.err.println("-------------------------------------------");
		try {
			MultipartFile file = form.getFileUpload().getFileData();
			String fileName = null;
			InputStream inputStream = null;
			// OutputStream outputStream = null;
			if (file.getSize() > 0) {
				inputStream = file.getInputStream();
				if (file.getSize() > 10000) {
					System.out.println("File Size:::" + file.getSize());
					fileName = file.getOriginalFilename();
					// outputStream = new FileOutputStream(fileName);
					System.out
							.println("fileName:" + file.getOriginalFilename());
					// InputStream inp = new FileInputStream(fileName);
					POIFSFileSystem fs = new POIFSFileSystem(inputStream);
					HSSFWorkbook wb = new HSSFWorkbook(fs);// .create(inputStream);
					Sheet sheet = wb.getSheetAt(0);
					
					List<Match> matches = new ArrayList<Match>();
					for(int rowId=0; rowId<=sheet.getLastRowNum();rowId++){
						if(rowId==0){
							continue;
						}
						Row row = sheet.getRow(rowId);
						Cell matchNoc = row.getCell(0);
						Cell matchLocationc = row.getCell(1);
						Cell matchDateTimec = row.getCell(2);
						Cell matchOpponent1c = row.getCell(3);
						Cell matchOpponentPts1c = row.getCell(4);
						Cell matchOpponent2c = row.getCell(5);
						Cell matchOpponentPts2c = row.getCell(6);
						Cell matchTiePtsc = row.getCell(7);
						Cell matchNoResultPtsc = row.getCell(8);
						
						Integer matchNo = new Integer((int) matchNoc.getNumericCellValue());
						String matchLocation = matchLocationc.getStringCellValue();
						
						Date matchDateTimed=matchDateTimec.getDateCellValue();
						System.out.println(matchDateTimed.getHours());
						System.out.println(matchDateTimed.getMinutes());
						//Calendar matchDateTime = Calendar.getInstance(TimeZone.getTimeZone ("America/New_York"));
						Calendar matchDateTimer = Calendar.getInstance();
						matchDateTimer.setTime(matchDateTimed);
						/*
						System.out.println(matchDateTime.get(Calendar.MINUTE));
						System.out.println(matchDateTime.get(Calendar.HOUR));
						System.out.println(matchDateTime.get(Calendar.HOUR_OF_DAY));
						
						//matchDateTime.setTimeInMillis(matchDateTime.getTimeInMillis());
						matchDateTime.set(Calendar.HOUR, matchDateTimed.getHours());
						matchDateTime.set(Calendar.MINUTE, matchDateTimed.getMinutes());
						matchDateTime.set(Calendar.DAY_OF_MONTH, matchDateTimed.getDate());
						matchDateTime.set(Calendar.MONTH, matchDateTimed.getMonth());
						matchDateTime.set(Calendar.YEAR, matchDateTimed.getYear()+1900);
						System.out.println(matchDateTime.get(Calendar.MINUTE));
						System.out.println(matchDateTime.get(Calendar.HOUR));
						System.out.println(matchDateTime.get(Calendar.HOUR_OF_DAY));*/
						String matchOpponent1=matchOpponent1c.getStringCellValue();
						Integer matchOpponentPts1= new Integer((int) matchOpponentPts1c.getNumericCellValue());; 
						String matchOpponent2=matchOpponent2c.getStringCellValue();
						Integer matchOpponentPts2= new Integer((int) matchOpponentPts2c.getNumericCellValue());;
						Integer matchTiePts= new Integer((int) matchTiePtsc.getNumericCellValue());;
						Integer matchNoResultPts= new Integer((int) matchNoResultPtsc.getNumericCellValue());;
						// authorization needed
						String updateUserId="initUser";
						
						Match match = new Match(matchNo,  matchLocation, form.getSelected(),
								matchDateTimed,  matchOpponent1,
								 matchOpponentPts1,  matchOpponent2,
								 matchOpponentPts2,  matchTiePts,
								 matchNoResultPts,  updateUserId);
						matches.add(match);
					}
					matchService.create(matches);

					return "redirect:/admin/matches/all";
				}
				inputStream.close();
			}

			// ..........................................
			session.setAttribute("uploadFile", file.getOriginalFilename());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/forms/uploadfileindex";
	}
	
	@RequestMapping(value="all", method=RequestMethod.GET)
	public String getView( Model model) {
		Collection<Match> matches = matchService.getAllMatches();

		model.addAttribute("matches", matches);
		return "/matches/view";
	}
}